﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace Noria.CssTool
{
    class Base64SpriteWorker
    {
        private readonly string _file;
        private string[] _lines;
        private IDictionary<int, string> _revised;

        public Base64SpriteWorker(string file)
        {
            _file = file;
        }

        public void DoWork()
        {
            LoadFile();
            Process();
            SaveFile();
        }


        private void SaveFile()
        {
            using (StreamWriter sw = new StreamWriter(_file))
            {
                for (int i = 0; i < _lines.Length; i++)
                {
                    if (_revised.ContainsKey(i))
                    {
                        sw.WriteLine("/*" + _lines[i] + "*/");
                        sw.WriteLine(_revised[i]);
                    }
                    else
                    {
                        sw.WriteLine(_lines[i]);
                    }
                }
            }
        }

        private void Process()
        {
            _revised = new Dictionary<int, string>();
            var baseDir = new FileInfo(_file).DirectoryName;

            for (int i = 0; i < _lines.Length; i++)
            {
                var line = _lines[i];
                if (!line.TrimStart().StartsWith("/*") && !line.Contains("url(data") && !line.Contains("url(\"data") && line.Contains("url("))
                {
                    var begin = line.IndexOf("url(") + 4;
                    var end = line.IndexOf(")", begin);

                    var img = line.Substring(begin, end - begin);
                    img = img.Trim('"');

                    var imgPath = Path.Combine(baseDir, img);
                    if (!File.Exists(imgPath))
                    {
                        //throw new CssException(i + 1, new FileNotFoundException(img));
                        Logger.Error("#{0}, File not found: -> {1}", i + 1, img);
                        continue;
                    }

                    var ext = new FileInfo(imgPath).Extension.ToLower().TrimStart('.');
                    var content = File.ReadAllBytes(imgPath);
                    var base64 = Convert.ToBase64String(content);

                    var sb = new StringBuilder();
                    sb.Append(line.Substring(0, begin));
                    sb.AppendFormat("data:image/{0};base64,", ext);
                    sb.Append(base64);
                    sb.Append(line.Substring(end));

                    _revised.Add(i, sb.ToString());
                }
            }
        }

        private void LoadFile()
        {
            if (File.Exists(_file))
            {
                if ((File.GetAttributes(_file) & FileAttributes.ReadOnly) != 0)
                {
                    File.SetAttributes(_file, (File.GetAttributes(_file) & ~FileAttributes.ReadOnly));
                    Logger.Info("remove readonly attrib to file {0}", _file);
                }

                _lines = File.ReadAllLines(_file);
            }
            else
            {
                throw new FileNotFoundException(_file);
            }
        }
    }
}